<?php

namespace App\Http\Controllers\Api;

use App\Jobs\SendWechatTemplate;
use App\Models\BackOrder;
use App\Models\Banner;
use App\Models\BookComment;
use App\Models\BookStockRemindUser;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\SellOrder;
use App\Models\SellOrderItem;
use App\Models\User;
use App\Models\UserAccountRecord;
use Illuminate\Http\Request;
use DB;
use EasyWeChat;
use EasyWeChat\Factory;

class UserController extends BaseController
{
    public function home(Request $request)
    {
        $user = User::query()->where('id',$this->user_id)->first();

        $info = [
            'wechat_avatar'     => $user->wechat_avatar,
            'wechat_nickname'   => $user->wechat_nickname,
        ];


        $sell_account = SellOrder::query()->where('state',5)->where('user_id',$this->user_id)->sum('actual_price');

        $buy_book_order_num = Order::query()->where('user_id',$this->user_id)->where('state','!=',0)->count();
        $sell_book_order_num = SellOrder::query()->where('user_id',$this->user_id)->count();
        $remind_num = BookStockRemindUser::query()->where('user_id',$this->user_id)->count();

        $banner = Banner::query()->where('position',5)->where('is_show',1)->first();
        $result = [
            'info'                  => $info,
            'sell_account'          => $sell_account,
            'buy_book_order_num'    => $buy_book_order_num,
            'sell_book_order_num'   => $sell_book_order_num,
            'remind_num'            => $remind_num,
            'banner' => [
                'image' => !empty($banner) ? $banner->image : '',
                'url' => !empty($banner) ? $banner->url : '',
            ]
        ];
        return $this->ok($result);
    }

    public function checkOfficialAccount(Request $request)
    {
        $user = User::find($this->user_id);

        $wechat_user = DB::table('wechat_users')->where('unionid',$user->unionid)->first();

        $subscribe = 0;
        if(!empty($wechat_user))
        {
            $subscribe = 1;
        }

        $data = [
            'subscribe' => $subscribe
        ];
        return $this->ok($data);
    }

    public function accountRecords(Request $request)
    {
        $page         = intval($request->get('page',1));
        $page         = max($page ,1);
        $page_size    = intval($request->get('page_size',10));

        $user = User::find($this->user_id);
        $columns = ['id','type','account','remark','created_at'];
        $list = UserAccountRecord::query()->where('user_id',$this->user_id)->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'          => $item->id,
                    'type'        => $item->type,
                    'account'     => $item->account,
                    'remark'      => $item->remark,
                    'created_at'  => $item->created_at->toDateTimeString(),
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"   => $items,
            "account" => $user->account,
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function bookRemind(Request $request)
    {
        $page         = intval($request->get('page',1));
        $page         = max($page ,1);
        $page_size    = intval($request->get('page_size',10));

        $list = BookStockRemindUser::query()->with(['book'])->where('user_id',$this->user_id)->orderBy('id','desc')->paginate($page_size,['*'],'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $stock_arr = [];
                $discount_arr = [];
                $price_arr = [];

                $discount_arr2 = [];
                $price_arr2 = [];
                if($item->book->new_book_stock > 0)
                {
                    $stock_arr[] = $item->book->new_book_stock;
                    $discount_arr2[] = $item->book->new_book_discount;
                    $price_arr2[] = $item->book->new_book_price;
                }
                else
                {
                    $discount_arr[] = $item->book->new_book_discount;
                    $price_arr[] = $item->book->new_book_price;
                }

                if($item->book->good_book_stock > 0)
                {
                    $stock_arr[] = $item->book->good_book_stock;
                    $discount_arr2[] = $item->book->good_book_discount;
                    $price_arr2[] = $item->book->good_book_price;
                }
                else
                {
                    $discount_arr[] = $item->book->good_book_discount;
                    $price_arr[] = $item->book->good_book_price;
                }

                if($item->book->medium_book_stock > 0)
                {
                    $stock_arr[] = $item->book->medium_book_stock;
                    $discount_arr2[] = $item->book->medium_book_discount;
                    $price_arr2[] = $item->book->medium_book_price;
                }
                else
                {
                    $discount_arr[] = $item->book->medium_book_discount;
                    $price_arr[] = $item->book->medium_book_price;
                }

                if($item->book->medium_book_stock2 > 0)
                {
                    $stock_arr[] = $item->book->medium_book_stock2;
                    $discount_arr2[] = $item->book->medium_book_discount2;
                    $price_arr2[] = $item->book->medium_book_price2;
                }
                else
                {
                    $discount_arr[] = $item->book->medium_book_discount2;
                    $price_arr[] = $item->book->medium_book_price2;
                }

                if($item->book->medium_book_stock3 > 0)
                {
                    $stock_arr[] = $item->book->medium_book_stock3;
                    $discount_arr2[] = $item->book->medium_book_discount3;
                    $price_arr2[] = $item->book->medium_book_price3;
                }
                else
                {
                    $discount_arr[] = $item->book->medium_book_discount3;
                    $price_arr[] = $item->book->medium_book_price3;
                }

                if($item->book->medium_book_stock4 > 0)
                {
                    $stock_arr[] = $item->book->medium_book_stock4;
                    $discount_arr2[] = $item->book->medium_book_discount4;
                    $price_arr2[] = $item->book->medium_book_price4;
                }
                else
                {
                    $discount_arr[] = $item->book->medium_book_discount4;
                    $price_arr[] = $item->book->medium_book_price4;
                }

                if($item->book->medium_book_stock5 > 0)
                {
                    $stock_arr[] = $item->book->medium_book_stock5;
                    $discount_arr2[] = $item->book->medium_book_discount5;
                    $price_arr2[] = $item->book->medium_book_price5;
                }
                else
                {
                    $discount_arr[] = $item->book->medium_book_discount5;
                    $price_arr[] = $item->book->medium_book_price5;
                }

                if($item->book->medium_book_stock6 > 0)
                {
                    $stock_arr[] = $item->book->medium_book_stock6;
                    $discount_arr2[] = $item->book->medium_book_discount6;
                    $price_arr2[] = $item->book->medium_book_price6;
                }
                else
                {
                    $discount_arr[] = $item->book->medium_book_discount6;
                    $price_arr[] = $item->book->medium_book_price6;
                }

                $min_discount = 0;
                $min_price = 0.0;
                $is_more = 0;
                if(count($stock_arr) > 1)
                {
                    $is_more = 1;
                }

                if(count($stock_arr) == 0)
                {
                    if(!empty($discount_arr))
                    {
                        $min_discount = min($discount_arr);
                    }
                    if(!empty($price_arr))
                    {
                        $min_price = min($price_arr);
                    }
                }
                else
                {
                    if(!empty($discount_arr2))
                    {
                        $min_discount = min($discount_arr2);
                    }
                    if(!empty($price_arr2))
                    {
                        $min_price = min($price_arr2);
                    }
                }

                $items[] = [
                    'id'                 => $item->id,
                    'book_id'            => $item->book_id,
                    'user_id'            => $item->user_id,
                    'title'              => $item->book->title,
                    'image'              => $item->book->image,
                    'author'             => $item->book->author,
                    'medium_book_price'  => $item->book->medium_book_price,
                    'total_stock'        => $item->book->total_stock,
                    'is_more'            => $is_more,
                    'min_discount'       => $min_discount,
                    'min_price'          => $min_price,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"   => $items,
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function getMoney(Request $request)
    {
        $money = $request->get('money');
        if(empty($money))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::find($this->user_id);
        if($user->account <= 0)
        {
            return $this->err(1,200,'','账户余额不足');
        }

        if($money > $user->account)
        {
            return $this->err(1,200,'','不能大于账户余额');
        }

        if($money < 0.4)
        {
            return $this->err(1,200,'','提现至少0.4元起');
        }

        $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
        if(empty($wechat_user))
        {
            return $this->err(1,200,'','请先关注公众号');
        }

        $partner_trade_no = time().mt_rand(000,999);
        //账户余额记录
        $record = UserAccountRecord::create([
            'type'              => 1,
            'account'           => $money,
            'remark'            => '提现到微信',
            'user_id'           => $this->user_id,
            'is_get_money'      => 1,
            'state'             => 0,
            'partner_trade_no'  => $partner_trade_no,
            'error_json'        => '',
            'success_json'      => '',
        ]);

        $amount = $money*100;
        $openid = $wechat_user->openid;

        $payment = EasyWeChat::payment(); // 微信支付
        $result = $payment->transfer->toBalance([
            'partner_trade_no'  => $partner_trade_no, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid'            => $openid,
            'check_name'        => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name'      => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount'            => $amount, // 企业付款金额，单位为分
            'desc'              => '提现账户余额', // 企业付款操作说明信息。必填
        ]);
        //dd($result);
        if($result['result_code'] === 'SUCCESS')
        {
            $record->update(['state'=>1,'success_json'=>json_encode($result,JSON_UNESCAPED_UNICODE)]);
            $user->decrement('account',$money);

            //使用异步队列
            $job_params = [
                'user_id'           => $user->id,
                'template_id'       => 'WVlGoIcGZPWVbHoSn6eeZE62G_cuZRgKtO9K35JhufM',
                'keyword1'          => $money.'元',
                'keyword2'          => date('Y-m-d H:i:s',$this->time),
                'keyword3'          => $user->account.'元',
            ];
            dispatch(new SendWechatTemplate($job_params));

            return $this->ok([],'提现成功');
        }

        $record->update(['error_json' => json_encode($result), 'state' => 2]);
        return $this->err(1,200,'','提现失败');
    }

    public function backOrders(Request $request)
    {
        $page         = intval($request->get('page',1));
        $page         = max($page ,1);
        $page_size    = intval($request->get('page_size',10));

        $builder = BackOrder::query()->with(['back_order_items.book'])->where('user_id',$this->user_id)->where('state','>',0);
        $columns = ['id','user_id','state','created_at','no'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);
        //dd($list);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'                => $item->id,
                    'user_id'           => $item->user_id,
                    'created_at'        => $item->created_at,
                    'no'                => $item->no,
                    'state'             => $item->state,
                    'books'             => $item->back_order_items,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"   => $items,
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function sellOrders(Request $request)
    {
        $page         = intval($request->get('page',1));
        $page         = max($page ,1);
        $page_size    = intval($request->get('page_size',20));

        $builder = SellOrder::query()->with(['sell_order_items'])->where('user_id',$this->user_id);
        $columns = ['id','user_id','state','total_price','actual_price','created_at'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);
        //dd($list);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $fail_books_num = SellOrderItem::query()->where('sell_order_id',$item->id)->where('state','!=',1)->count();
                $items[] = [
                    'id'                => $item->id,
                    'created_at'        => $item->created_at,
                    'state'             => $item->state,
                    'total_price'       => $item->total_price,
                    'actual_price'      => $item->actual_price,
                    'books_total'       => count($item->sell_order_items),
                    'fail_books_num'    => $fail_books_num,
                    'books'             => $item->sell_order_items
                ];
            }
        }

        //$order_total_count = SellOrder::query()->where('user_id',$this->user_id)->where('state',5)->count();
        $order_total_price = SellOrder::query()->where('user_id',$this->user_id)->where('state',5)->sum('actual_price');
        $order_success_books = SellOrderItem::query()->where('user_id',$this->user_id)->where('state',1)->count();

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"   => $items,
            "total"   => [
                "order_total_count" => $order_success_books,
                "order_total_price" => $order_total_price,
            ]
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    /**
     * 卖过的书
     * @param Request $request
     */
    public function sellOrderBooks(Request $request)
    {
        $page         = intval($request->get('page',1));
        $page         = max($page ,1);
        $page_size    = intval($request->get('page_size',10));

        $orders = SellOrder::query()->where('state','>',2)->where('user_id',$this->user_id)->get();
        $order_ids = collect($orders)->pluck('id');

        //$list = SellOrderItem::query()->with(['sell_order'=>function($query){
            //$query->where('state','>','2');
        //}])->where('user_id',$this->user_id)->orderBy('id','desc')->paginate($page_size,['*'],'page',$page);

        $list = SellOrderItem::query()->whereIn('sell_order_id',$order_ids)->where('user_id',$this->user_id)->orderBy('id','desc')->paginate($page_size,['*'],'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'            => $item->id,
                    'sell_order_id' => $item->sell_order_id,
                    'book_id'       => $item->book_id,
                    'book_title'    => $item->book_title,
                    'book_image'    => $item->book_image,
                    'book_author'   => $item->book_author,
                    'review'        => $item->review,
                    'is_review'     => $item->is_review,
                    'reviewed_at'   => $item->reviewed_at,
                    'review_state'  => $item->review_state,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"   => $items,
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function orderBooks(Request $request)
    {
        $page         = intval($request->get('page',1));
        $page         = max($page ,1);
        $page_size    = intval($request->get('page_size',10));

        $orders = Order::query()->where('state','>',1)->where('user_id',$this->user_id)->get();
        $order_ids = collect($orders)->pluck('id');

        //$list = OrderItem::query()->with(['order'=>function($query){
            //$query->where('state','>',1);
        //}])->where('user_id',$this->user_id)->orderBy('id','desc')->paginate($page_size,['*'],'page',$page);

        $list = OrderItem::query()->where('user_id',$this->user_id)->whereIn('order_id',$order_ids)->orderBy('id','desc')->paginate($page_size,['*'],'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'            => $item->id,
                    'order_id'      => $item->order_id,
                    'book_id'       => $item->book_id,
                    'type'          => $item->type,
                    'book_title'    => $item->book_title,
                    'book_image'    => $item->book_image,
                    'book_author'   => $item->book_author,
                    'review'        => $item->review,
                    'is_review'     => $item->is_review,
                    'reviewed_at'   => $item->reviewed_at,
                    'review_state'  => $item->review_state,
                ];
            }
        }

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"   => $items,
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function sellBookComment(Request $request)
    {
        $id      = intval($request->get('id'));
        $review  = trim(($request->get('review')));

        if(empty($id) || empty($review))
        {
            return $this->err(1,200,'','参数错误');
        }

        $row = SellOrderItem::query()->where('id',$id)->first();
        if(empty($row) || $row->user_id != $this->user_id)
        {
            return $this->err(1,200,'','记录不存在');
        }

        if($row->is_review)
        {
            return $this->err(1,200,'','请勿重复评价');
        }

        $row->update(['is_review'=>1,'reviewed_at'=>$this->time,'review'=>$review]);

        $user = User::find($this->user_id);
        $comment = BookComment::create([
            'type'            => 2,
            'user_nickname'   => $user->wechat_nickname,
            'user_avatar'     => $user->wechat_avatar,
            'created_at'      => $this->time,
            'updated_at'      => $this->time,
            'content'         => $review,
            'book_id'         => $row->book_id,
            'order_items_id'  => $id,
            'state'           => 0,
        ]);
        $comment->user()->associate($user);
        $comment->save();

        return $this->ok([],'评价成功');
    }

    public function comment(Request $request)
    {
        $id      = intval($request->get('id'));
        $review  = trim(($request->get('review')));

        if(empty($id) || empty($review))
        {
            return $this->err(1,200,'','参数错误');
        }

        $row = OrderItem::find($id);
        if(empty($row) || $row->user_id != $this->user_id)
        {
            return $this->err(1,200,'','记录不存在');
        }

        if($row->is_review)
        {
            return $this->err(1,200,'','请勿重复评价');
        }

        $row->update(['is_review'=>1,'reviewed_at'=>$this->time,'review'=>$review]);

        $user = User::find($this->user_id);
        $comment = BookComment::create([
            'type'            => 2,
            'user_nickname'   => $user->wechat_nickname,
            'user_avatar'     => $user->wechat_avatar,
            'created_at'      => $this->time,
            'updated_at'      => $this->time,
            'content'         => $review,
            'book_id'         => $row->book_id,
            'order_items_id'  => $id,
            'state'           => 0,
        ]);
        $comment->user()->associate($user);
        $comment->save();

        return $this->ok([],'评价成功');
    }

    public function myRecommendUsers(Request $request)
    {
        $list = User::query()->where('recommend_user_id',$this->user_id)->get();

        $items = [];
        $number = 0;
        if(!empty($list))
        {
            foreach ($list as $v)
            {
                if($v->is_recommend_coupon)
                {
                    $number++;
                }
                $items[] = [
                    'wechat_avatar'         => $v->wechat_avatar,
                    'wechat_nickname'       => $v->wechat_nickname,
                    'is_recommend_coupon'   => $v->is_recommend_coupon,
                ];
            }
        }

        $data = [
            'num'   => count($items),
            'money' => $number*20,
            'items' => $items,
        ];
        return $this->ok($data);
    }

    public function recommendUserInfo(Request $request)
    {
        $recommend_user_id = intval($request->get('recommend_user_id'));
        if(empty($recommend_user_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $user = User::query()->where('id',$recommend_user_id)->first();
        if(empty($user))
        {
            return $this->err(1,200,'','邀请者不存在');
        }

        $data = [
            'recommend_user_id' => $recommend_user_id,
            'wechat_avatar'     => $user->wechat_avatar,
            'wechat_nickname'   => $user->wechat_nickname
        ];
        return $this->ok($data);
    }
}
